<template>
  <div class="td-image">
    <ul class="td-image-list">
      <draggable
        v-model="imgs"
        @change="dragChange"
        :options="{ animation: 300 }"
      >
        <li
          v-for="(img, i) in imgs"
          :key="i"
          class="item-img"
          :style="{ width: width, height: width }"
        >
          <el-image :src="img" :preview-src-list="imgs"></el-image>

          <!-- 删除按钮 -->
          <span v-if="preview" class="btn-image-delete" @click="remove(img, i)">
            <i class="el-icon-delete"></i>
          </span>
        </li>
      </draggable>
    </ul>
  </div>
</template>

<script>
import draggable from 'vuedraggable'

export default {
  name: 'TdImage',
  components: {
    draggable
  },
  model: {
    prop: 'list',
    event: 'updateImgs'
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },

    // 每张图片的宽度
    width: {
      type: String,
      default: '120px'
    },

    // 显示删除按钮
    type: {
      type: String,
      default: 'drag'
    }
  },
  data() {
    return {
      imgs: []
    }
  },

  computed: {
    preview() {
      return this.type !== 'preview'
    }
  },

  watch: {
    list(val) {
      this.imgs = val
    }
  },

  methods: {
    dragChange({ moved }) {
      this.$emit('drag-change', moved)
      this.$emit('updateImgs', this.imgs)
    },

    async remove(img, i) {
      try {
        const res = await this.$confirm('确定移除该图片吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.imgs.splice(i, 1)
        this.$emit('remove', { img, index: i })
        this.$emit('updateImgs', this.imgs)
      } catch (err) {
        console.log(err)
      }
    }
  },

  mounted() {
    this.imgs = this.list
  }
}
</script>

<style lang="scss" scoped>
.td-image-list {
  .item-img {
    // width: 100px;
    // height: 100px;
    display: inline-block;
    margin-top: 10px;
    border: 1px solid #ddd;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
    margin-right: 10px;

    &:hover {
      transition: all 0.3s;
      box-shadow: 0 0 10px 4px #999;

      .btn-image-delete {
        transition: all 0.3s;
        transform: translateY(0);
      }
    }
  }
  // li + li {
  //   margin-right: 10px;
  // }

  .btn-image-delete {
    width: 100%;
    height: 30px;
    line-height: 30px;
    display: block;
    position: absolute;
    bottom: 0;
    left: 0;
    background: rgba($color: #000000, $alpha: 0.3);
    text-align: center;
    cursor: pointer;
    transform: translateY(34px);

    &:hover {
      background: rgba($color: #000000, $alpha: 0.5);
    }

    i {
      font-size: 18px;
      color: #fff;
    }
  }
}
</style>
